﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace FirePHP
{
	public class FirePHP
	{
		protected const string FirePHPItemName = "FirePHPHeadersSent";
		protected const string FirePHPIncrementor = "FirePHPIncrement";

		public FirePHP()
		{
			if (!headersSent())
				SendHeaders();
		}

		protected bool headersSent() {
			return HttpContext.Current.Items.Contains(FirePHPItemName);
		}

		protected void SendHeaders() {
			var headers = HttpContext.Current.Response.Headers;
			headers.Add("X-Wf-Protocol-1", "http://meta.wildfirehq.org/Protocol/JsonStream/0.2");
			headers.Add("X-Wf-1-Plugin-1", "http://meta.firephp.org/Wildfire/Plugin/FirePHP/Library-FirePHPCore/0.3");
			headers.Add("X-Wf-1-Structure-1", "http://meta.firephp.org/Wildfire/Structure/FirePHP/FirebugConsole/0.1");
			HttpContext.Current.Items[FirePHPItemName] = true;
		}

		protected int GetNextId() {
			if(!HttpContext.Current.Items.Contains(FirePHPIncrementor)) {
				HttpContext.Current.Items[FirePHPIncrementor] = 1;
				return 1;
			}
			int id = 0;
			if(!int.TryParse((string)HttpContext.Current.Items[FirePHPIncrementor], out id)) {
				HttpContext.Current.Items[FirePHPIncrementor] = 1;
				return 1;
			}
			id++;
			HttpContext.Current.Items[FirePHPIncrementor] = id;
			return id;
		}

		public void Log(string message)
		{
			SendMessage(GetMessageBody(message, MessageType.LOG));
		}

		public void Warn(string message)
		{
			SendMessage(GetMessageBody(message, MessageType.WARN));
		}

		public void Error(string message)
		{
			SendMessage(GetMessageBody(message, MessageType.ERROR));
		}

		protected void SendMessage(string messageBody)
		{
			HttpContext.Current.Response.Headers.Add("X-Wf-1-1-1-" + GetNextId(), messageBody.Length + "|" + messageBody + "|");
		}

		protected string GetMessageBody(string message, MessageType type)
		{
			StringBuilder body = new StringBuilder();
			body.Append("[{\"Type\":\"" + type.ToString() + "\"},");
			body.Append("\"" + message.Replace("\"", "&quot;") + "\"");
			body.Append("]");
			return body.ToString();
		}

		protected enum MessageType
		{
			LOG, WARN, ERROR
		}
	}
}
